<?php
/**
 * 快递查询接口
 * Created by PhpStorm.
 * User: tiemeng
 * Date: 16/3/28
 * Time: 18:19
 */
class Kd{
    private $_requestData = [];
    private $_EBusinessID = "1256509";
    private $_appKey = "c9a69711-ea5f-46db-9854-ae0aed1be162";
    private $_requestType = 1002;
    private $_dataType = 2;
    private $_url = "http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx";
    public function getLogisticDetail($shipperCode,$logisticCode){
        $this->_requestData['ShipperCode'] = $shipperCode;
        $this->_requestData['LogisticCode'] = $logisticCode;
        $reqData = [
            'RequestData' => json_encode($this->_requestData),
            'EBusinessID' => $this->_EBusinessID,
            'RequestType' => $this->_requestType,
            'DataType'    => $this->_dataType
        ];
        $signData = $this->_sign(json_encode($this->_requestData));
        $reqData['DataSign'] = $signData;
        $logisticInfo = $this->post($this->_url,$reqData);
        return $logisticInfo;
    }

    private function _sign($data){
        return urlencode(base64_encode(md5($data.$this->_appKey)));
    }

    /**
     * post
     * post方式请求资源
     * @param string $url       基于的baseUrl
     * @param array $keysArr    请求的参数列表
     * @param int $flag         标志位
     * @return string           返回的资源内容
     */
    public function post($url, $keysArr, $flag = 0){
        $ch = curl_init();
        if(! $flag) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $keysArr);
        curl_setopt($ch, CURLOPT_URL, $url);
        $ret = curl_exec($ch);

        curl_close($ch);
        return $ret;
    }
}
